03. SQLAlchemy Object Lifecycle — Part 1

SQLAlchemy Object Lifecycle - Part 1 Heading

SQLAlchemy Object Lifecycle — Part 1

Recall

We can insert new records into the database using SQLAlchemy by running

person = Person(name='Amy')
db.session.add(person)
db.session.commit()

which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit() .

ND004 C01 L04 03 SQLAlchemy Object Lifecycle - Part 1

SQLAlchemy Object Lifecycle - Part 1 Recap

Takeaways

  • Within a session, we create transactions every time we want to commit work to the database.
  • Proposed changes are not immediately committed to the database and instead go through stages to allow for undos.
  • The ability to undo is allowed via db.session.rollback()

Stages:

  1. Transient : an object exists, it was defined.
  user1 = User(name='Amy')

…but not attached to a session (yet).

  1. Pending : an object was attached to a session. "Undo" becomes available via db.session.rollback() . Waits for a flush to happen

  2. Flushed : about ready to be committed to the database, translating actions into SQL command statements for the engine.

  3. Committed : manually called for a change to persist to the database (permanently); session's transaction is cleared for a new set of changes.

Stage Quiz

QUIZ QUESTION: :

Match the statement to the stage that an object would be in its lifecycle, if the statement was called

ANSWER CHOICES:



Statement

Stage

flushed

committed

transient

pending

pending

committed

transient

transient

pending

pending

SOLUTION:

Statement

Stage

committed

transient

transient

pending

pending

pending

pending

pending

pending

committed

transient

transient

transient

transient

pending

pending

pending

pending

pending

pending

Stage Q

QUIZ QUESTION: :

Order the stages in correct order

ANSWER CHOICES:



Stage Order

Stage

Pending

Transient

Committed

Flushed

SOLUTION:

Stage Order

Stage

Pending

Transient

Committed

Flushed

During what stage(s) is db.session.rollback() available?

SOLUTION:
  • Pending

Stage Quiz 2

When an object has been defined, it is in a ____ stage.

SOLUTION: Transient

Stage Quiz 3

When an object has been added on the database, it is in a ____ state.

SOLUTION: Committed

Stage Quiz 4

When an object has been associated to a session, but not yet committed to a database, what stage(s) could it be in? Check all that apply

SOLUTION:
  • Pending
  • Flushed

Stage Quiz 5

What is the difference between a flush and a commit?

SOLUTION: A commit persists changes to the database; a flush does not